/*$(function() {  
    FastClick.attach(document.body);  
});*/
var filechooser = document.getElementById("filePath");
  //    用于压缩图片的canvas
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext('2d');
  //    瓦片canvas
  var tCanvas = document.createElement("canvas");
  var tctx = tCanvas.getContext("2d");
  var maxsize = 100 * 1024;
  $("#upload").on("click", function() {
        filechooser.click();
      })
      .on("touchstart", function() {
        $(this).addClass("touch")
      })
      .on("touchend", function() {
        $(this).removeClass("touch")

      });
      
  filechooser.onchange = function() {
	//	debugger;
	    var $file = $(this);
		var fileObj = $file[0];
		var windowURL = window.URL || window.webkitURL;
		var dataURL;
				//var $p =$(this).parent().siblings(".show_pic");
		var $p =$(".show_pic");
		var $imgLength = $(".show_pic").children().length;
		var $num =3-$imgLength;
		if(fileObj && fileObj.files){
			if(fileObj.files.length > 3 || $imgLength >= 3  || fileObj.files.length+ $imgLength > 3){
			    alert("最多只能选择三个图片,你还能上传"+ $num +"个图片")
			    return false;
			}				
			for(var i =0; i< fileObj.files.length; i++){
				var  field ="";
				if(i== 0)
					field = "filePicture";
				if(i == 1)
					field = "filePicture2";
				if(i == 2)
					field = "filePicture3";
				if( fileObj.files[i]){
					dataURL = windowURL.createObjectURL(fileObj.files[i]);	
					var $img='<span>'
								+'<img src="' + dataURL + '" style="width: 100px;height: 100px;" alt="评论图片" filed ="'+field+'"  />'
								+'<span style=""><img src="'+rootPath+'/image/add_del.png" alt="" /></span>'
					        +'</span>';
					$p.append($img);
				}else{
					dataURL = $file.val();
					//var imgObj = $(this).parent().siblings(".show_pic > span > img");
					// 两个坑:
					// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
					// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
				//	imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
				//		imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
					var $img='<span>'
						+'<img src="' + dataURL + '" style="width: 100px;height: 100px;" alt="评论图片" filed ="'+field+'"  />'
						+'<span style=""><img src="'+rootPath+'/image/add_del.png" alt="" /></span>'
			        +'</span>';
		          	$p.append($img);
				}
			}
		}   
		var idd = $(".myevaluatecontent .photo input").attr("id");
		//alert("idd:"+idd)
		ajaxUploadFiles(idd);
  };
  
  
  
  

//上传评论图片，并生成评论记录
function ajaxUploadFiles(filePathId){
	var filePicture = $("#filePicture").val();
	var filePicture2 = $("#filePicture2").val();
	var filePicture3 = $("#filePicture3").val();
	var orderId = "1234";
	var url =rootPath + "/consultComment/addConsultCommentPic";
	$.ajaxFileUpload({
		  url:url,//需要链接到服务器地址   
		  type:'post',
		  data:{'filePicture':filePicture,'filePicture2':filePicture2,"filePicture3":filePicture3},
	      secureuri:false,  
	      fileElementId:filePathId,//文件选择框的id属性  
	      dataType: 'JSON',   //json 
	      success: function (result) {  
	    	 // alert(JSON.stringify(result))
	    	  result =JSON.parse($(result).text());
	    	  if(result.resultSuccess == true){
	    		  var filePicture = result.filePicture;
	    		  if(filePicture!=null && filePicture!=undefined){
	    			//  console.log(filePicture)
	    			  $("#filePicture").val(filePicture);
	    		  }
	    		  var filePicture2 = result.filePicture2;
	    		  if(filePicture2!=null && filePicture2!=undefined){
	    			  $("#filePicture2").val(filePicture2);
	    			//  console.log(filePicture2);
	    		  }
	    		  var filePicture3 = result.filePicture3;
	    		  if(filePicture3!=null && filePicture3!=undefined){
	    			  $("#filePicture3").val(filePicture3);
	    			//  console.log(filePicture3)
	    		  }
	    		}else if(result.resultSuccess == false){
	    		    alert("图片上传失败")
	    		}
	    	  
	      }, 
	      error : function(data, status, e){ 
	    	 alert("图片上传失败"+e);
	      } 
	});
}

//      使用canvas对大图片进行压缩
function compress(img) {
    var initSize = img.src.length;
    var width = img.width;
    var height = img.height;
    //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
    var ratio;
    if ((ratio = width * height / 4000000) > 1) {
      ratio = Math.sqrt(ratio);
      width /= ratio;
      height /= ratio;
    } else {
      ratio = 1;
    }
    canvas.width = width;
    canvas.height = height;
//        铺底色
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //如果图片像素大于100万则使用瓦片绘制
    var count;
    if ((count = width * height / 1000000) > 1) {
      count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
//            计算每块瓦片的宽和高
      var nw = ~~(width / count);
      var nh = ~~(height / count);
      tCanvas.width = nw;
      tCanvas.height = nh;
      for (var i = 0; i < count; i++) {
        for (var j = 0; j < count; j++) {
          tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
          ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
        }
      }
    } else {
      ctx.drawImage(img, 0, 0, width, height);
    }
    //进行最小压缩
    var ndata = canvas.toDataURL('image/jpeg', 0.1);
//  console.log('压缩前：' + initSize);
//  console.log('压缩后：' + ndata.length);
//  console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
    return ndata;
}
  //    图片上传，将base64的图片转成二进制对象，塞进formdata上传
  function upload(basestr, type, $li) {
    var text = window.atob(basestr.split(",")[1]);
    var buffer = new Uint8Array(text.length);
    var pecent = 0, loop = null;
    for (var i = 0; i < text.length; i++) {
      buffer[i] = text.charCodeAt(i);
    }
    var blob = getBlob([buffer], type);
    var xhr = new XMLHttpRequest();
    var formdata = getFormData();
    formdata.append('imagefile', blob);
    xhr.open('post', '/cupload');
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var jsonData = JSON.parse(xhr.responseText);
        var imagedata = jsonData[0] || {};
        var text = imagedata.path ? '上传成功' : '上传失败';
        console.log(text + '：' + imagedata.path);
        clearInterval(loop);
        //当收到该消息时上传完毕
        $li.find(".progress span").animate({'width': "100%"}, pecent < 95 ? 200 : 0, function() {
          $(this).html(text);
        });
        if (!imagedata.path) return;
//      $(".pic-list").append('<a href="' + imagedata.path + '">' + imagedata.name + '（' + imagedata.size + '）<img src="' + imagedata.path + '" /></a>');
      }
    };
    //数据发送进度，前50%展示该进度
    xhr.upload.addEventListener('progress', function(e) {
      if (loop) return;
      pecent = ~~(100 * e.loaded / e.total) / 2;
      $li.find(".progress span").css('width', pecent + "%");
      if (pecent == 50) {
        mockProgress();
      }
    }, false);
    //数据后50%用模拟进度
    function mockProgress() {
      if (loop) return;
      loop = setInterval(function() {
        pecent++;
        $li.find(".progress span").css('width', pecent + "%");
        if (pecent == 99) {
          clearInterval(loop);
        }
      }, 100)
    }
    xhr.send(formdata);
  }
  /**
   * 获取blob对象的兼容性写法
   * @param buffer
   * @param format
   * @returns {*}
   */
  function getBlob(buffer, format) {
    try {
      return new Blob(buffer, {type: format});
    } catch (e) {
      var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
      buffer.forEach(function(buf) {
        bb.append(buf);
      });
      return bb.getBlob(format);
    }
  }
  /**
   * 获取formdata
   */
  function getFormData() {
    var isNeedShim = ~navigator.userAgent.indexOf('Android')
        && ~navigator.vendor.indexOf('Google')
        && !~navigator.userAgent.indexOf('Chrome')
        && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
    return isNeedShim ? new FormDataShim() : new FormData()
  }
  /**
   * formdata 补丁, 给不支持formdata上传blob的android机打补丁
   * @constructor
   */
  function FormDataShim() {
    console.warn('using formdata shim');
    var o = this,
        parts = [],
        boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
        oldSend = XMLHttpRequest.prototype.send;
    this.append = function(name, value, filename) {
      parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
      if (value instanceof Blob) {
        parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
        parts.push(value);
      }
      else {
        parts.push('\r\n\r\n' + value);
      }
      parts.push('\r\n');
    };
    // Override XHR send()
    XMLHttpRequest.prototype.send = function(val) {
      var fr,
          data,
          oXHR = this;
      if (val === o) {
        // Append the final boundary string
        parts.push('--' + boundary + '--\r\n');
        // Create the blob
        data = getBlob(parts);
        // Set up and read the blob into an array to be sent
        fr = new FileReader();
        fr.onload = function() {
          oldSend.call(oXHR, fr.result);
        };
        fr.onerror = function(err) {
          throw err;
        };
        fr.readAsArrayBuffer(data);
        // Set the multipart content type and boudary
        this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
        XMLHttpRequest.prototype.send = oldSend;
      }
      else {
        oldSend.call(this, val);
      }
    };
  }